# Copyright(C) 2023. Huawei Technologies Co.,Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse
from pathlib import Path
from queue import Queue

import numpy as np
import yaml
from timer import timer
from yacs.config import CfgNode
import onnxruntime as ort
from ais_bench.infer.interface import InferSession
import jieba

from utils.syn_utils import get_chunks, str2bool, get_frontend, run_frontend, denorm


def get_phone_ids(frontend, sentence, merge_sentences, get_tone_ids, args):
    frontend_dict = run_frontend(
        frontend=frontend,
        text=sentence,
        merge_sentences=merge_sentences,
        get_tone_ids=get_tone_ids,
        lang=args.lang)
    phone_ids = frontend_dict['phone_ids']
    # merge_sentences=True here, so we only use the first item of phone_ids
    phone_ids = phone_ids[0].numpy().astype(np.int64)
    return phone_ids


def encoder_infer_with_chunk(phone_ids, encoder, encoder_input_name, block_size, pad_size):
    encoder_outputs = encoder.run(None, {encoder_input_name: phone_ids})
    chunked_output = get_chunks(encoder_outputs[0], block_size, pad_size)
    chunk_num = len(chunked_output)
    return chunked_output, chunk_num


def generate_wav(chunked_output, chunk_num, decoder, postnet, vocoder, block_size, pad_size, mode, CUSTOM_SIZE, am_mu, am_std):
    mel_outputs = []
    for i, chunk in enumerate(chunked_output):
        before_output = decoder.infer([chunk], mode, custom_sizes=CUSTOM_SIZE)
        postnet_output = postnet.infer([before_output[0].transpose((0, 2, 1))], mode,
                                          custom_sizes=CUSTOM_SIZE)
        after_output = before_output + postnet_output[0].transpose((0, 2, 1))
        normalized_mel = after_output[0]
        sub_mel = denorm(normalized_mel, am_mu, am_std)
        sub_mel = sub_mel[0]
        if i == 0:
            sub_mel = sub_mel[:-pad_size]
        elif i == chunk_num - 1:
            # the last chunk's right side must not have enough pad
            sub_mel = sub_mel[pad_size:]
        else:
            # the right side of the last few chunks may not have enough pad
            sub_mel = sub_mel[pad_size:(block_size + pad_size) - sub_mel.shape[0]]

        mel_outputs.append(sub_mel)
    mel = np.concatenate(mel_outputs, axis=0)

    # vocoder
    wav = vocoder.infer([mel], mode, custom_sizes=CUSTOM_SIZE)
    return wav, mel


def evaluate(tts_in_queue, tts_out_queue, args):

    # Init config and input sentences
    with open(args.am_config) as f:
        am_config = CfgNode(yaml.safe_load(f))
    with open(args.voc_config) as f:
        voc_config = CfgNode(yaml.safe_load(f))

    print("========Args========")
    print(yaml.safe_dump(vars(args)))
    print("========Config========")
    print(am_config)
    print(voc_config)

    # frontend
    frontend = get_frontend(
        lang=args.lang,
        phones_dict=args.phones_dict,
        tones_dict=args.tones_dict)

    with open(args.phones_dict, "r") as f:
        phn_id = [line.strip().split() for line in f.readlines()]
    vocab_size = len(phn_id)
    print("vocab_size:", vocab_size)

    output_dir = Path(args.output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)
    am_mu, am_std = np.load(args.am_stat)
    merge_sentences = True
    get_tone_ids = False

    N = 0
    T = 0
    CUSTOM_SIZE = 1000000
    sentence_id = 0
    block_size = args.block_size
    pad_size = args.pad_size

    #load model
    ort_session_encoder_infer = ort.InferenceSession(args.am_encoder_infer)
    decoder_om = InferSession(args.device_id, args.am_decoder_om)
    postnet_om = InferSession(args.device_id, args.am_postnet_om)
    vocoder_om = InferSession(args.device_id, args.voc_om)
    encoder_input_name = ort_session_encoder_infer.get_inputs()[0].name
    jieba.initialize()
    mode = "dymshape"
    print('================ TTS warm up ===================')

    # warm up
    sentences_warm = {'text': '你好，我是华为的小智，很高兴为您服务。', 'is_end': False}
    phone_ids_warm = get_phone_ids(frontend, sentences_warm['text'], merge_sentences, get_tone_ids, args)
    chunked_output_warm, chunk_num_warm = encoder_infer_with_chunk(phone_ids_warm, ort_session_encoder_infer,
                                                                   encoder_input_name, block_size, pad_size)
    wav_warm, mel_warm = generate_wav(
        chunked_output_warm,
        chunk_num_warm,
        decoder_om,
        postnet_om,
        vocoder_om,
        block_size,
        pad_size,
        mode,
        CUSTOM_SIZE,
        am_mu,
        am_std
    )
    print('================ TTS ready ===================')

    while True:
        if not tts_in_queue.empty():
            sentences = tts_in_queue.get()
            sentence = sentences['text']
            end_tag = sentences['is_end']
            with timer() as t:
                phone_ids = get_phone_ids(frontend, sentence, merge_sentences, get_tone_ids, args)
                #acoustic model
                chunked_output, chunk_num = encoder_infer_with_chunk(phone_ids, ort_session_encoder_infer,
                                                                     encoder_input_name, block_size, pad_size)
                wav, mel = generate_wav(
                    chunked_output,
                    chunk_num,
                    decoder_om,
                    postnet_om,
                    vocoder_om,
                    block_size,
                    pad_size,
                    mode,
                    CUSTOM_SIZE,
                    am_mu,
                    am_std
                )

            # save wav
            wav = wav[0]
            N += wav.size
            T += t.elapse
            speed = wav.size / t.elapse
            rtf = am_config.fs / speed
            silence = np.zeros((int(0.2 * 24000), 1))
            wav = np.concatenate((silence, wav, silence), axis=0)
            print(f"{sentence_id}, mel: {mel.shape}, wave: {wav.shape}, time: {t.elapse}s, Hz: {speed}, RTF: {rtf}.")
            tts_out_queue.put((wav, end_tag))
            # print(f"generation speed: {N / T}Hz, RTF: {am_config.fs / (N / T)}")
            print('================ TTS done, waiting for next text ===================')
            sentence_id += 1
            continue


def parse_args():
    # parse args and config
    parser = argparse.ArgumentParser(
        description="Synthesize with acoustic model & vocoder")
    # acoustic model
    parser.add_argument(
        '--am',
        type=str,
        default='fastspeech2_csmsc',
        choices=['fastspeech2_csmsc'],
        help='Choose acoustic model type of tts task.')
    parser.add_argument(
        '--am_config', type=str, default=None, help='Config of acoustic model.')
    parser.add_argument(
        '--am_ckpt',
        type=str,
        default=None,
        help='Checkpoint file of acoustic model.')
    parser.add_argument(
        "--am_stat",
        type=str,
        default=None,
        help="mean and standard deviation used to normalize spectrogram when training acoustic model."
    )
    parser.add_argument(
        "--phones_dict", type=str, default=None, help="phone vocabulary file.")
    parser.add_argument(
        "--tones_dict", type=str, default=None, help="tone vocabulary file.")

    # vocoder
    parser.add_argument(
        '--voc',
        type=str,
        default='pwgan_csmsc',
        choices=[
            'pwgan_csmsc',
            'mb_melgan_csmsc',
            'style_melgan_csmsc',
            'hifigan_csmsc',
        ],
        help='Choose vocoder type of tts task.')
    parser.add_argument(
        '--voc_config', type=str, default=None, help='Config of voc.')
    parser.add_argument(
        '--voc_ckpt', type=str, default=None, help='Checkpoint file of voc.')
    parser.add_argument(
        "--voc_stat",
        type=str,
        default=None,
        help="mean and standard deviation used to normalize spectrogram when training voc."
    )
    parser.add_argument(
        '--voc_onnx', type=str, default=None, help='Onnx model of voc.')
    # other
    parser.add_argument(
        '--lang',
        type=str,
        default='zh',
        help='Choose model language. zh or en')

    parser.add_argument(
        "--inference_dir",
        type=str,
        default=None,
        help="dir to save inference models")

    parser.add_argument(
        "--device_id", type=int, default=1, help="device id of npu to use.")
    parser.add_argument(
        "--text",
        type=str,
        help="text to synthesize, a 'utt_id sentence' pair per line.")
    # streaming related
    parser.add_argument(
        "--am_streaming",
        type=str2bool,
        default=True,
        help="whether use streaming acoustic model")
    parser.add_argument(
        "--block_size", type=int, default=42, help="block size of am streaming")
    parser.add_argument(
        "--pad_size", type=int, default=12, help="pad size of am streaming")

    parser.add_argument("--output_dir", type=str, help="output dir.")
    parser.add_argument("--am_encoder_infer", type=str, help="the am encoder model path.")
    parser.add_argument("--am_decoder", type=str, help="the am decoder model path.")
    parser.add_argument("--am_postnet", type=str, help="the am postnet model path.")

    parser.add_argument("--am_decoder_om", type=str, help="the am decoder om model path.")
    parser.add_argument("--am_postnet_om", type=str, help="the am postnet om model path.")
    parser.add_argument('--voc_om', type=str, default=None, help='Om model of voc.')

    args = parser.parse_args()
    return args


def main():
    args = parse_args()

    in_queue = Queue()
    out_queue = Queue()
    evaluate(in_queue, out_queue, args)


if __name__ == "__main__":
    main()
